class Main extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            list: [],
            id: 0,
            pagesize: 15,
            start: 1,
            imgsrc: '',
            name: '',
            type: '-1',
            typeindex: 'FW',
            price: '',
            counts: [],
            pagestart: 0,
            orders: 1,
            jumppath: '',
            // cid:1,
        };
    }

    formatlist(list) {
        console.log('formatlist', list);

        var listitem = [], wulist = []
        if (list.length > 0) {
            list.forEach((x, i) => {
                listitem.push(
                    <tr key={i}>
                        <td className="tdimgbox"><p className="td-img"><img src={`${API_HEAD}imgs/${x.picpath}`} /></p></td>
                        <td>{x.jumppath || '-'}</td>
                        <td onClick={this.setshow.bind(this, x.id, x.state)} className="tconter">{x.state == "ON" ? "显示" : "隐藏"}</td>
                        <td onClick={this.toorder.bind(this, x.id)} className="tconter">{x.orders}</td>
                        <td className="operatebox">
                            <div className='operate' id={"ope" + x.id}>
                                <div>
                                    <img src="./src/edit.png" />
                                    <p data-toggle="modal" data-target="#modalOne" className='edit' onClick={this.todetail.bind(this, x.id)}>编辑</p>
                                </div>
                                <div>
                                    <img src="./src/del.png" />
                                    <p className='edit colred' onClick={this.del.bind(this, x.id)}>删除</p>
                                </div>
                            </div>
                        </td>
                    </tr>
                )
            });
        } else {
            wulist.push(
                <p className="wulist">暂无数据</p>
            )
        }
        this.setState({ listitem, list, originallist: list, wulist })
    }
    // 编辑
    todetail(e) {
        var { list, imgsrc } = this.state, item = [];
        list.forEach(x => {
            if (x.id == e) {
                imgsrc = `${API_HEAD}imgs/${x.picpath}`
                this.setState({ id: e, imgsrc, jumppath: x.jumppath, })
            }
        });
        // console.log(item, 'item')
    }
    // 排序
    toorder(id) {
        let orders = prompt("请输入1-999的正整数")
        if (orders == "" || orders == null) {
            return;
        }
        if (isNaN(orders) || orders < 1 || orders > 999) {
            return;
        }
        this.setState({ showloading: 'ON' })
        orders = Math.floor(orders);
        swipersetorders({ id, orders }, res => {
            if (res.issuccess == 1) {
                alert("设置成功");
                // this.flist(res.list);
                this.freshlist();
            } else {
                this.setState({ showloading: '' })
                alert("设置失败");
            }
        });
    }
    // 显示隐藏
    // setshow(e, i) {
    //     this.setState({ showloading: 'ON' })
    //     swipersetshow(e, res => {
    //         if (res.issuccess == 1) {
    //             alert(`${i == "ON" ? '隐藏' : '显示'}成功`)
    //             this.freshlist()
    //         } else {
    //             this.setState({ showloading: '' })
    //             alert(`${i == "ON" ? '隐藏' : '显示'}失败`)
    //         }
    //     })

    // }
    // 删除
    del(e) {
        this.setState({ delid: e }, () => {
            $('#myModal').modal('toggle');
        })
    }
    confirmdel() {
        this.setState({ showloading: 'ON' })
        let { delid, start } = this.state
        删除工单(delid, res => {
            $('#myModal').modal('toggle');
            if (res.success == 1) {
                this.freshlist()
            } else {
                this.setState({ showloading: '' })
                alert(res.msg);
            }
        })
    }

    setpager(pagecount, start) {
        let counts = [];
        for (let i = 0; i < pagecount; i++) {
            counts.push(start + i)
        }
        console.log(counts, 'counts');
        this.setState({ counts, pagestart: 0 })
    }
    clickpage(e) {
        let { start, pagesize } = this.state
        start = (e * pagesize) + 1
        this.setState({ pagestart: e, start }, () => {
            this.freshlist()
        })
    }
    setpage(e) {
        let { pagesize, start } = this.state
        pagesize = parseInt(e)
        start = 1
        this.setState({ pagesize, start }, () => {
            this.freshlist()
        })
    }




    submit() {
        var { imgsrc, type, price, name } = this.state, that = this, err = '', imgarr = [];

        if (!imgsrc) err = "请添加图片"
        if (name == '') err = "请输入名称"
        if (type == '-1') err = "请输入名称"
        if (isNaN(price) || Number(price) < 0) err = "请输入正确的价格"

        if (err.length > 0) {
            alert(err);
        } else {
            this.setState({ showloading: 'ON' }, () => {
                that.uploadimg({ imgsrc, type, price: Number(price) * 100, name })
            })
        }

    }

    componentDidMount() {
        let that = this
        laydate.render({
            elem: '#test1', //指定元素
            type: 'datetime',
            done: function (value, date, endDate) {
                that.setState({ startdate: value })
            }
        });
        laydate.render({
            elem: '#test2', //指定元素
            type: 'datetime',
            done: function (value, date, endDate) {
                that.setState({ enddate: value })
            }
        });
        // let that = this;
        this.setState({ showloading: '' })
        this.setState({ showloading: 'ON', }, () => {
            this.freshlist()

        })

    }

    freshlist() {
        let { typeindex, start, pagesize, startdate, enddate } = this.state, err = '';
        console.log(startdate, enddate, 'startdate,enddate');

        if (startdate) {
            if (!enddate) {
                err = '结束时间不能为空'
            } else {
                if (new Date(startdate).getTime() > new Date(enddate).getTime()) {
                    err = '开始时间必须小于结束时间'
                } else {
                    startdate = new Date(startdate).getTime() / 1000;
                    enddate = new Date(enddate).getTime() / 1000;
                }
            }
        }
        if (err != '') {
            alert(err)
        } else {

            获取工单列表({ start, pagesize, startdate, enddate }, res => {
                let { list } = res;
                if (start == 1) {
                    let pagecount = Math.ceil(res.total / pagesize);
                    this.setpager(pagecount, start);
                    this.setState({ start, total: res.total })

                }
                this.setState({ showloading: '', list })
            })
        }

    }

    filechange(e) {
        var that = this;
        let reader = new FileReader();
        reader.onload = function (e) {
            const workbook = XLSX.read(e.target.result); // 从原始数据获取工作簿

            var first_sheet_name = workbook.SheetNames[0]; // 获得第一个工作表名称

            const worksheet = workbook.Sheets[first_sheet_name]; // 获取工作表

            let json = XLSX.utils.sheet_to_json(worksheet);
            console.log(worksheet, 'worksheet'); // 读取并打印A1端元格数据
            console.log(json, 'json'); // 读取并打印A1端元格数据

            if (json.length > 0) {
                let list = []
                json.forEach(x => {
                    list.push({
                        wxdh: x['维修编号']
                        , wxzt: x['维修状态']
                        , carnumber: x['车牌号码']
                        , carcolor: x['车辆颜色']
                        , wxlb: x['维修类别']
                        , khmc: x['客户名称']
                        , wxje: x['维修金额']
                        , cllx: x['车辆类型']
                        , qcpp: x['汽车品牌']
                        , sclc: x['上次里程（公里）']
                        , djsj: parseInt(xlsxtoJsDate(x['登记时间']).getTime() / 1000)
                        , gender: x['性别']
                        , phone: x['手机号']
                        , ljcz: x['余额']
                        , wxxm: x['最近项目']

                    })
                    //身份证号码	姓名	性别	手机号码	工作单位	人员类别
                })
                let jsonstr = JSON.stringify(list)

                test1(jsonstr, res => {
                    if (res.issuccess) {
                        alert('导入成功')
                        that.freshlist()
                    }
                })


                console.log(jsonstr, 'jsonstr');
            }


        };
        reader.readAsArrayBuffer($('#file1')[0].files[0]);

    }


    // 图片
    filechangeimg(e) {
        var that = this;
        var filedata = $('#file' + e)[0].files[0];
        let _name, _fileName, filedatasize = 2048;

        _name = $('#file' + e)[0].value;
        _fileName = _name.substring(_name.lastIndexOf(".") + 1).toLowerCase();
        if (_fileName !== "png" && _fileName !== "jpg" && _fileName !== "gif" && _fileName !== "jpeg") {
            alert("上传图片格式不正确，请重新上传");
        } else {
            if (filedatasize < filedata.size / 1024) {
                alert("上传图片不能大于2M");
                return;
            }

            let filee = e
            var reader = new FileReader();
            reader.readAsDataURL(filedata);
            reader.onload = function (e) {
                var base64str = e.target.result;
                that.putswiperimglistdata([base64str], filee)
            }
        }
    }
    putswiperimglistdata(target, prop) {
        let imgsrc = '', that = this;
        if (prop == 'lb') {
            let lbhtml = [], { lbarr } = that.state
            imgsrc = target[0]
            if (!isBase64(imgsrc)) {
                if (imgsrc.indexOf(`${API_HEAD}`) == -1) {
                    imgsrc = `${API_HEAD}imgs/${imgsrc}`

                }
            }
            lbarr.push(imgsrc)
            lbarr.forEach((x, i) => {
                lbhtml.push(
                    <div className="img_warp">
                        <img src={x} className="img" />
                        <img className='closeimg' onClick={this.del_lbimg.bind(this, i, 'lb')} src='./src/img_close.png' />
                    </div>
                )
            })
            this.setState({ lbhtml, lbarr })
        } else {
            imgsrc = target[0]
            if (!isBase64(imgsrc)) {
                if (imgsrc.indexOf(`${API_HEAD}`) == -1) {
                    imgsrc = `${API_HEAD}imgs/${imgsrc}`

                }
            }
            that.setState({ [prop]: imgsrc })
        }

        // this.setState({
        //     imgsrc, smallimg,// lbimgsrc, lbimgsrcarr
        // })

    }
    clickupload(e) {
        $('#file' + e).click();
    }
    del_img(prop) {
        this.setState({ [prop]: '' })

    }
    // 上传图片
    uploadimg(data) {
        console.log(data, 'uploadimg--data');

        uploadimg(data.imgsrc, res => {
            if (res.issuccess == 1) {
                // x = `${API_HEAD}imgs/${res.path}`
                data['imgsrc'] = res.path
                添加分类(data, res => {
                    this.setState({ showloading: '' })
                    if (res.issuccess == 1) {
                        that.setState({ imgsrc: '', id: 0, name: '', price: '', type: '-1' })
                        alert(`${this.state.id > 0 ? '修改' : '保存'}成功`);
                        that.freshlist()
                    } else {
                        alert(res.msg)
                    }
                })

            } else {
                alert(res.msg)
                err = 1
                return;
            }
        })




        // let uploadimgarr = [],
        //     {  imgsrc,  jumppath} = this.state, that = this;
        // arr.forEach((x, i) => {
        //     if (x.indexOf(`${API_HEAD}`) == -1) {
        //         if (isBase64(x)) {

        //         }
        //     } else {
        //         uploadimgarr.push(x)
        //     }
        // })
        // if (uploadimgarr.length == arr.length) {
        //     uploadimgarr.forEach((x, i) => {
        //         imgsrc = x.replace(`${API_HEAD}imgs/`, '')
        //     })

        //     var data = { picpath:imgsrc };
        //     if (this.state.id > 0) {
        //         data['id'] = this.state.id;
        //     }
        //     console.log(data, 'data');



        // } else {
        //     this.setState({ showloading: '' })
        //     alert('图片上传失败')
        // }

    }


    selectchange(e) {
        console.log(e.target.value, 'selectchange');
        this.setState({ type: e.target.value })
    }
    inputchange(prop, e) {
        // let { target } = this.state;
        // target[prop] = e.target.value
        // this.setState({ target })
        this.setState({ [prop]: e.target.value })
    }
    add() {
        this.setState({ imgsrc: '', id: 0, jumppath: '', })
        // $('#modalOne').modal('toggle');
    }
    clicktype(e) {
        this.setState({ typeindex: e }, () => {
            this.freshlist()
        })

    }
    setprice(id) {
        var price = prompt('请输入价格')
        console.log(price, 'promot');
        if (isNaN(price)) {
            alert('请输入正确的价格')
        } else {
            分类修改价格({ id, price: Number(price) * 100 }, res => {
                if (res.issuccess == 1) {
                    this.freshlist()
                } else {
                    this.setState({ showloading: '' })
                    alert(res.msg);
                }
            })
        }
    }

    render() {
        let { list, wxzt, wxbh, wxlb,khmc,wxje,cllx,qcpp, sclc,   counts, pagestart, startdate, enddate } = this.state;
        console.log(list, 'list');

        return (
            <div className="breadLinebox">
                <input type="file" id='file1' onChange={this.filechange.bind(this)} style={{ display: "none" }} />
                <Loading hidden={this.state.showloading != 'ON'} />
                <Modal content='确定要删除吗？' click={this.confirmdel.bind(this)} />

                {/* <th>维修编号</th>
                                    <th>维修状态</th>
                                    <th>车牌号码</th>
                                    <th>车辆颜色</th>
                                    <th>维修类别</th>
                                    <th>客户名称</th>
                                    <th>维修金额</th>
                                    <th>车辆类型</th>
                                    <th>汽车品牌</th>
                                    <th>上次里程（公里）</th>
                                    <th>登记时间</th> */}
                                     {/* <td>{x.wxdh}</td>
                                                <td>{x.wxzt}</td>
                                                <td>{x.carnumber}</td>
                                                <td>{x.carcolor}</td>
                                                <td>{x.wxlb}</td>
                                                <td>{x.khmc}</td>
                                                <td>{x.wxje}</td>
                                                <td>{x.cllx}</td>
                                                <td>{x.qcpp}</td>
                                                <td>{x.sclc}</td> */}

                <div className="modal fade" id="modalOne" >
                    <div className="modal-dialog">
                        <div className="modal-content">
                            <div className="modal-header border">
                                <p className="modal-title">{this.state.id > 0 ? "编辑" : "新建"}</p>
                                <img data-dismiss="modal" src="./src/close.png" />
                            </div>
                            <div className="modal-body">
                               
                                <div className="input-group">
                                    <span className="input-group-addon">维修编号</span>
                                    <input id='name' onChange={this.inputchange.bind(this, 'wxbh')} value={wxbh} type="text" placeholder='请输入维修编号' className="input" />
                                </div>
                                <div className="input-group">
                                    <span className="input-group-addon">维修状态</span>
                                    <input id='name' onChange={this.inputchange.bind(this, 'wxzt')} value={wxzt} type="text" placeholder='请输入维修状态' className="input" />
                                </div>
                                 <div className="input-group">
                                    <span className="input-group-addon">车牌号码</span>
                                    <input id='name' onChange={this.inputchange.bind(this, 'wxbh')} value={wxbh} type="text" placeholder='请输入车牌号码' className="input" />
                                </div>
                                <div className="input-group">
                                    <span className="input-group-addon">车辆颜色</span>
                                    <input id='name' onChange={this.inputchange.bind(this, 'wxzt')} value={wxzt} type="text" placeholder='请输入车辆颜色' className="input" />
                                </div>
                                 <div className="input-group">
                                    <span className="input-group-addon">维修类别</span>
                                    <input id='name' onChange={this.inputchange.bind(this, 'wxlb')} value={wxlb} type="text" placeholder='请输入维修类别' className="input" />
                                </div>
                                <div className="input-group">
                                    <span className="input-group-addon">客户名称</span>
                                    <input id='name' onChange={this.inputchange.bind(this, 'khmc')} value={khmc} type="text" placeholder='请输入客户名称' className="input" />
                                </div>
                                 <div className="input-group">
                                    <span className="input-group-addon">维修金额</span>
                                    <input id='name' onChange={this.inputchange.bind(this, 'wxje')} value={wxje} type="text" placeholder='请输入维修金额' className="input" />
                                </div>
                                 <div className="input-group">
                                    <span className="input-group-addon">车辆类型</span>
                                    <input id='name' onChange={this.inputchange.bind(this, 'cllx')} value={cllx} type="text" placeholder='请输入车辆类型' className="input" />
                                </div>
                                <div className="input-group">
                                    <span className="input-group-addon">汽车品牌</span>
                                    <input id='name' onChange={this.inputchange.bind(this, 'qcpp')} value={qcpp} type="text" placeholder='请输入汽车品牌' className="input" />
                                </div>
                                <div className="input-group">
                                    <span className="input-group-addon">上次里程（公里）</span>
                                    <input id='name' onChange={this.inputchange.bind(this, 'sclc')} value={sclc} type="text" placeholder='请输入上次里程（公里）' className="input" />
                                </div>
                            </div>
                            <div className="modal-footer border">
                                <button type="button" className="closemod" data-dismiss="modal">关闭</button>
                                <button type="button" onClick={this.submit.bind(this)} data-dismiss="modal" className="submitmod">提交</button>
                            </div>

                        </div>
                    </div>
                </div>
                <div className='content_wrap panel-default content_wrap'>
                    <div className="breadLine">
                        <div className="img">
                            <img src='./src/lm_order1.png' />
                            工单管理
                        </div>
                    </div>
                    <div className="content">
                        {/* <div style={{display:clicknew?"":"none"}} id="div"> */}

                        <div className="tabletit" >
                            {/* <p className="delall"><img src="./src/delall.png"/>批量删除</p> */}

                            <p className="add" data-toggle="modal" data-target="#modalOne" style={{ cursor: 'pointer' }} onClick={this.add.bind(this)}>新建</p>
                            <p className="add" onClick={() => {
                                $('#file1').click();
                            }} >导入</p>

                            <div className="inputbox">
                                <input type="text" id="test1" placeholder='请选择开始日期' value={startdate} className="input" />
                                <span>-</span>
                                <input type="text" id="test2" placeholder='请选择结束日期' value={enddate} className="input" />
                            </div>
                            <p className="add" onClick={() => {
                                this.freshlist()
                            }} >查询</p>

                            {/* <div className="typelist">
                                <p onClick={this.clicktype.bind(this,'FW')}className={typeindex=='FW'?'c':''}>服务</p>
                                <p onClick={this.clicktype.bind(this,'YL')}className={typeindex=='YL'?'c':''}>娱乐</p>
                                <p onClick={this.clicktype.bind(this,'YD')}className={typeindex=='YD'?'c':''}>运动</p>
                            </div> */}
                        </div>
                        <table className="tab">
                            <thead>
                                <tr>
                                    <th>维修编号</th>
                                    <th>维修状态</th>
                                    <th>车牌号码</th>
                                    <th>车辆颜色</th>
                                    <th>维修类别</th>
                                    <th>客户名称</th>
                                    <th>维修金额</th>
                                    <th>车辆类型</th>
                                    <th>汽车品牌</th>
                                    <th>上次里程（公里）</th>
                                    <th>登记时间</th>
                                    {/* <th className="tconter">状态<span className="red">（点击切换）</span></th> */}
                                    {/* <th className="tconter">排序<span className="red">（点击修改）</span></th> */}
                                    <th className="cz tconter">操作</th>
                                </tr>
                            </thead>
                            <tbody>
                                {
                                    list.map((x, i) => {
                                        return (
                                            <tr key={i}>
                                                <td>{x.wxdh}</td>
                                                <td>{x.wxzt}</td>
                                                <td>{x.carnumber}</td>
                                                <td>{x.carcolor}</td>
                                                <td>{x.wxlb}</td>
                                                <td>{x.khmc}</td>
                                                <td>{x.wxje}</td>
                                                <td>{x.cllx}</td>
                                                <td>{x.qcpp}</td>
                                                <td>{x.sclc}</td>
                                                <td>{formatDate(new Date(x.djsj))}</td>
                                                {/* <td onClick={this.setshow.bind(this, x.id, x.state)} className="tconter">{x.state == "ON" ? "显示" : "隐藏"}</td> */}
                                                <td className="operatebox">
                                                    <div className='operate' id={"ope" + x.id}>
                                                        <div>
                                                            <img src="./src/edit.png" />
                                                            <p className='edit' onClick={()=>{window.location.href='./fixinfodetail.html?id='+x.id}}>查看</p>
                                                        </div>
                                                        <div>
                                                            <img src="./src/del.png" />
                                                            {/* <p className='edit colred' onClick={this.del.bind(this, x.id)}>删除</p> */}
                                                        </div>
                                                    </div>
                                                </td>
                                            </tr>
                                        )
                                    })
                                }
                            </tbody>
                        </table>
                        {this.state.wulist}

                        <div className="pagerbox">
                            <p>共{this.state.total}条</p>
                            <Pager counts={counts} click={this.clickpage.bind(this)} change={this.setpage.bind(this)} index={pagestart} />
                        </div>
                    </div>
                </div>
            </div>


        )


    }
}





ReactDOM.render(
    <div>
        <TopLine />
        <div id='body'>
            <LeftMenu code='fixinfo' />
            <Main />
        </div>
    </div>
    // <Barrage/>
    , $('.container')[0]
)